package com.hd.trans.ui.activity;


import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.hd.trans.R;
import com.hd.trans.TranslationInterior;
import com.hd.trans.TranslationUI;
import com.hd.trans.common.Constants;
import com.hd.trans.common.interf.Callback;
import com.hd.trans.db.DataBaseMgr;
import com.hd.trans.db.bean.TranslateRecord;
import com.hd.trans.framework.click.XClickUtil;
import com.hd.trans.framework.dialog.ConfirmDialog;
import com.hd.trans.ui.adapter.RecordTextAdapter;
import com.hd.trans.ui.base.BaseActivity;
import com.hd.trans.utils.ToastUtils;
import com.hd.trans.utils.TrackerForTrans;

import org.jetbrains.annotations.NotNull;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

public class TextHistoryActivity extends BaseActivity implements View.OnClickListener {

    private ImageView back;
    private TextView title;
    private TextView rightText, leftText;
    private RecyclerView recycler;
    private FrameLayout flBottom;
    private TextView tvDeleteItems;

    private RecordTextAdapter adapter;
    private ConfirmDialog dialog;
    private boolean isNation = false;//是否是民族文字翻译
    private boolean isFromTranslatePage = false;//是否是民族文字翻译
    private String titleName;

    public static void open(Context context) {
        Intent intent = new Intent(context, TextHistoryActivity.class);
        context.startActivity(intent);
    }

    public static void open(Context context, String titleName, boolean isNation) {
        Intent intent = new Intent(context, TextHistoryActivity.class);
        intent.putExtra("is_nation",isNation);
        intent.putExtra("title_name", titleName);
        context.startActivity(intent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        TranslationInterior.getTrackerListener().view(TrackerForTrans.WBFY+"结果页");
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_text_history;
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        isNation = getIntent().getBooleanExtra("is_nation", false);
        titleName = getIntent().getStringExtra("title_name");
        isFromTranslatePage = getIntent().getBooleanExtra("isFromTranslatePage", false);
        initView();
        initData();
    }

    private void initView() {
        back = (ImageView) findViewById(R.id.back);
        title = (TextView) findViewById(R.id.tilte);
        rightText = (TextView) findViewById(R.id.right_text);
        leftText = (TextView) findViewById(R.id.left_text);
        recycler = (RecyclerView) findViewById(R.id.recycler);
        flBottom = (FrameLayout) findViewById(R.id.fl_bottom);
        tvDeleteItems = (TextView) findViewById(R.id.tv_delete_items);

        title.setText(TextUtils.isEmpty(titleName) ? getResources().getString(R.string.history_text) : titleName);
        rightText.setText(getResources().getString(R.string.history_manager));
        tvDeleteItems.setText("删除记录");
        ((TextView)findViewById(R.id.tv_tips)).setText("暂无翻译记录");

        back.setOnClickListener(this);
        rightText.setOnClickListener(this);
        leftText.setOnClickListener(this);
        tvDeleteItems.setOnClickListener(this);

        recycler.setLayoutManager(new LinearLayoutManager(this));
        recycler.setItemAnimator(new DefaultItemAnimator());
        adapter = new RecordTextAdapter(null);
        adapter.setAnimationEnable(true);
        adapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.SlideInBottom);
        recycler.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> baseQuickAdapter, @NonNull View view, int position) {
                if(adapter.isManagerType()){
                    view.findViewById(R.id.check_box).performClick();
                }else {
                    long recordId = adapter.getData().get(position).getId();
                    if(isFromTranslatePage){
                        fromIntent.putExtra(Constants.HISTORY_RECORD_ID, recordId);
                        setResult(Constants.TEXT_HISTORY_RESULT_OK, fromIntent);
                    }else {
                        TranslationUI.openTextTransActivity(TextHistoryActivity.this, recordId);
                    }
                    finish();
                }
            }

        });
        adapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NotNull BaseQuickAdapter baseQuickAdapter, @NotNull View view, int position) {
                if(!adapter.isManagerType()){
                    entryManagerStatus();
                    adapter.setItemLongClickPosition(position);
                }
                return false;
            }
        });
        adapter.setCallbackListener(new Callback() {
            @Override
            public void onCallback() {
                if(adapter.getData().size() == adapter.getSelectedData().size()){
                    //全选状态
                    selectedAllStatus();
                }else {
                    //非全选状态
                    cancelSelectedAllStatus();
                }
            }
        });
    }


    private void initData() {
    }

    @Override
    protected void onResume() {
        refreshRecords();
        super.onResume();
    }

    /**
     * 刷新记录
     */
    private void refreshRecords() {
        Observable.create((ObservableOnSubscribe<List<TranslateRecord>>) emit -> {
            emit.onNext(DataBaseMgr.getInstance().getAllRecords(false, isNation));
            emit.onComplete();
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(bindToLifecycle())
                .subscribe(new DisposableObserver<List<TranslateRecord>>() {
                    @Override
                    public void onNext(List<TranslateRecord> list) {
                        adapter.setNewInstance(list);
                        if(list == null || list.isEmpty()){
                            recycler.setVisibility(View.GONE);
                            rightText.setVisibility(View.GONE);
                        }else {
                            recycler.setVisibility(View.VISIBLE);
                            rightText.setVisibility(View.VISIBLE);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    @Override
    public void onClick(View v) {
        if (XClickUtil.isFastDoubleClick(v, XClickUtil.INTERVAL_MILLIS)) {
            return;
        }
        int id = v.getId();
        if (id == R.id.back) {
            finish();
        } else if (id == R.id.right_text) {
            String rightTextStr = rightText.getText().toString();
            if (!adapter.isManagerType()) {
                //进入管理
                entryManagerStatus();
            } else if (rightTextStr.equals(getResources().getString(R.string.select_all))) {
                //全选
                adapter.selectAll(new Callback() {
                    @Override
                    public void onCallback() {
                        selectedAllStatus();
                    }
                });
            } else if (rightTextStr.equals(getResources().getString(R.string.cancel_select_all))) {
                //取消全选
                adapter.cancelSelectAll(new Callback() {
                    @Override
                    public void onCallback() {
                        cancelSelectedAllStatus();
                    }
                });

            }
        } else if (id == R.id.left_text) {
            //退出管理
            adapter.cancelSelectAll(new Callback() {
                @Override
                public void onCallback() {
                    exitManagerStatus();
                }
            });
        } else if (id == R.id.tv_delete_items) {
            //移出文本翻译记录/收藏夹
            if (dialog == null) {
                dialog = ConfirmDialog.builder()
                        .setContent(getResources().getString(R.string.confirm_tip))
                        .rightTxtColor(TranslationInterior.getThemeColor())
                        .setRightListenner(new ConfirmDialog.OnComfrimDialogListenner() {
                            @Override
                            public void OnComfrim(Dialog dialog) {
                                List<TranslateRecord> records = adapter.getSelectedData();
                                DataBaseMgr.getInstance().deleteRecords(records);

                                ToastUtils.showNormal("已删除" + titleName);
                                exitManagerStatus();
                                refreshRecords();
                            }
                        })
                        .build();
            }
            dialog.show(getSupportFragmentManager(), "TextHistoryActivity");
        }
    }

    private void entryManagerStatus(){
        leftText.setText(getResources().getString(R.string.history_exit_manager));
        back.setVisibility(View.GONE);
        leftText.setVisibility(View.VISIBLE);
        flBottom.setVisibility(View.VISIBLE);
        tvDeleteItems.setEnabled(false);
        rightText.setText(getResources().getString(R.string.select_all));
        rightText.setTextColor(getResources().getColor(R.color.primary_color));

        adapter.setShowType(true);
        adapter.notifyDataSetChanged();
    }

    private void exitManagerStatus(){
        adapter.setShowType(false);
        back.setVisibility(View.VISIBLE);
        leftText.setVisibility(View.GONE);
        flBottom.setVisibility(View.GONE);
        rightText.setText(getResources().getString(R.string.history_manager));
        rightText.setTextColor(getResources().getColor(R.color.primary_text_black));
    }

    private void selectedAllStatus(){
        //全选
        tvDeleteItems.setEnabled(true);
        tvDeleteItems.setBackgroundResource(R.drawable.shape_corner_blue_16);
        rightText.setText(getResources().getString(R.string.cancel_select_all));
    }

    private void cancelSelectedAllStatus(){
        //取消全选
        rightText.setText(getResources().getString(R.string.select_all));
        if(adapter.getSelectedData().size() == 0){
            tvDeleteItems.setEnabled(false);
            tvDeleteItems.setBackgroundResource(R.drawable.shape_corner_cccccc_16);
        }else {
            tvDeleteItems.setEnabled(true);
            tvDeleteItems.setBackgroundResource(R.drawable.shape_corner_blue_16);
        }
    }

    @Override
    public void onBackPressed() {
        if (back.getVisibility() == View.VISIBLE) {
            super.onBackPressed();
        } else {
            leftText.performClick();
        }
    }
}